package org.apache.ibatis.demo.test;

import org.apache.ibatis.executor.SimpleExecutor;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;
import org.junit.Before;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * @Date 2021/2/19 22:57
 * @Created mobian
 * @Description 编写执行器
 */
public class Demo2 {

  @Before
  public void init() throws Exception {
    String resource = "resources/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);

    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    configuration = sqlSessionFactory.getConfiguration();
    connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);

    jdbcTransaction = new JdbcTransaction(connection);

  }

  private Configuration configuration;
  private Connection connection;
  private JdbcTransaction jdbcTransaction;
  private final String JDBC_URL = "jdbc:mysql://localhost:3306/blog";
  private final String JDBC_USERNAME = "root";
  private final String JDBC_PASSWORD = "123456";

  @Test
  public void simpleExecutorTest() throws SQLException, IOException {
    String resource = "resources/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    //1、通过sqlSessionFactory获取对应的配置信息
    configuration = sqlSessionFactory.getConfiguration();

    //2、根据数据库基本信息，配置驱动的连接信息
    connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    //3、配置对应的事务
    jdbcTransaction = new JdbcTransaction(connection);

    //执行器需要两个参数：我们的配置信息、数据库的事务
    SimpleExecutor executor = new SimpleExecutor(configuration, jdbcTransaction);

    //执行器创建好之后，获取一个连接的实例，即指定对应的sql，用于执行对应的SQL
    MappedStatement mappedStatement = configuration.getMappedStatement("org.apache.ibatis.demo.dao.BlogMapper.selectBlog");

    //真正去执行对应的操作
    List<Object> lists = executor.doQuery(mappedStatement, 10, RowBounds.DEFAULT, executor.NO_RESULT_HANDLER, mappedStatement.getBoundSql(10));


    for (int i = 0; i < lists.size(); i++) {
      System.out.println(lists.get(i).toString());
    }
  }
}
